#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import paramiko


pkey = 'zhangfan_id_rsa'
key = paramiko.RSAKey.from_private_key_file(pkey, password='')  # 有解密密码时,


def getSShCon(ip):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # 通过公共方式进行认证 (不需要在known_hosts 文件中存在)
    ssh.connect(ip, port=11022, username='zhangfan', pkey=key)  # 这里要 pkey passwordkey 密钥文件
    return ssh


def doCmd(ip, cmd):
    # paramiko用于ssh连接远程服务器
    # 定义rsa
    # 创建ssh
    ssh = getSShCon(ip)
    stdin, stdout, stderr = ssh.exec_command(cmd)
    err = stderr.read().decode('utf-8')
    out = stdout.read().decode('utf-8')
    return out, err


def begin():
    # ips = ['139.199.4.247']
    ips = []

    # 建议使用圆括号将跨越多行的语句进行封装
    command = ("grep -a 'SCItemChangeMessage' /data/logs/web/badperson.808[0-1].log.2018-03-31-*.log"
               """| grep -a '"classId":0,"objId":2,"incrNum":-' > /home/zhangfan/xiaofei_%s_20180331_14.txt""")
    for ip in ips:
        cmd = command % ip  # 得到最终cmd
        print(cmd)
        out, err = doCmd(ip, cmd)
        print(err)
        print(out)


if __name__ == '__main__':
    begin()
